package org.openclinic.web.tag;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class AgeTag extends TagSupport {
	
	private static final long serialVersionUID = -9013098231039011120L;
	
	private Date birthdate;
	
	@Override
	public int doStartTag() throws JspException {
		try {
			Calendar cal1 = new GregorianCalendar();
			Calendar cal2 = new GregorianCalendar();
			int age = 0;
			int factor = 0;
			cal1.setTime(birthdate);
			if (cal2.get(Calendar.DAY_OF_YEAR) < cal1.get(Calendar.DAY_OF_YEAR)) {
				factor = -1;
			}
			age = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR) + factor;
			
			this.pageContext.getOut().print(age);
		} catch (IOException exception) {
			throw new JspException(exception.getMessage(), exception.getCause());
		}
		return super.doStartTag();
	}

	public void setBirthdate(Date birthdate) {
		this.birthdate = birthdate;
	}

}